do
    local pvp = pvp
	local COLORS = COLORS
    local factionTable = { ["Horde"] = 0, ["Alliance"] = 1}
	local roster = {}
	local last --last refresh
    local specHealers = {
		"Discipline","Holy","Mistweaver","Restoration",
    }
	
	--functions
	local RequestBattlefieldScoreData = RequestBattlefieldScoreData
	local GetNumBattlefieldScores = GetNumBattlefieldScores
	local GetBattlefieldScore = GetBattlefieldScore
	local UnitFactionGroup = UnitFactionGroup	
	local UnitName = UnitName
	local strmatch = strmatch
	local tinsert = tinsert
	local format = format
	local time = time
  
  
--------------------------------------------------------------------------------------------------
    local function GetOpponentRoster()
	--[[
		crawl through battleground scoreboard and store all the opposing team members
		returns a table of opposing team members names,specs,and realms
	--]]
        local r = {}
		
        local num = GetNumBattlefieldScores()
        local _,playerRealm = UnitName("player")
        local playerFaction = factionTable[UnitFactionGroup("player")]
      
        for i=1,num do
            local namerealm,_,_,_,_,faction,_,class,classToken,_,_,_,_,_,_,spec = GetBattlefieldScore(i)
            if faction ~= playerFaction then
                local name,realm = strmatch(namerealm,"(.-)%s*%-%s*(.+)")
                if not name then
                    name = namerealm
                    realm = playerRealm
                end
                r[name] = { class=class, token=classToken, spec=(spec or "?"), realm=realm }
            end
        end
		
		roster = r --want to store this 'globally' for looking up player specs faster
        return r
    end  

--------------------------------------------------------------------------------------------------
    local function Sort(roster)
	--[[
		sorts realm lists from least to most for display
	--]]
        local realmList = {}
        local sorted = {}
        local most

        for p in pairs(roster) do
            local realm = roster[p].realm
            if not realmList[realm] then realmList[realm]={} end   
            tinsert(realmList[realm],p) --p is the name of a player
        end

        --r is the name of a server
        for r in pairs(realmList) do
            local players = realmList[r]
            local count = #(players)
            local index = 1
            for i,j in ipairs(sorted) do --j is a table of player names
                local stored = #(j)
                if count == stored then --same count, can list before or after this entry
                    index = i
                    break
                elseif count > stored then --more players, list after this entry
                    index = i + 1
                end
            end
            tinsert(sorted,index,players)
        end
       
        return sorted
    end
  
--------------------------------------------------------------------------------------------------
    local function SpyPrintLocal()
    --[[ 
		broadcast spy information to player only
		this and SpyPrintGlobal have a lot of overlap, should probably clean that up
	--]]    
        local roster = GetOpponentRoster()
        local sorted = Sort(roster) --ordered (least to most) table of tables of player names
		local COLORS = COLORS
		local count = 0
		local hstr = ""
		local hcount = 0		
		local fmt = pvp.settings.spy.localtext
		
		local color = pvp.settings.spy.color
		color = format("|cff%.2x%.2x%.2x",color.r*255,color.g*255,color.b*255) --create open color code thingy
		
		pvp:Print("|cffff0000Spy report:|r")
		for i,players in ipairs(sorted) do
			local pcount = #(players)
			count = count + pcount --total player count
			local realm = roster[players[1]].realm.." - " --get realm name from first player encountered
			for j,player in ipairs(players) do
				local cc = COLORS[roster[player].token] 
				local class = roster[player].class
				local spec = roster[player].spec
				local keys = {
					["name"] = format("|cff%.2x%.2x%.2x%s|r",cc.r*255,cc.g*255,cc.b*255,player)..color,
					["class"] = class,
					["spec"] = spec,
					["altclass"] = pvp.settings.alt.class[class],
					["altspec"] = pvp.settings.alt.spec[class][spec],
				} --variable substitutions available for use
				
				local str = pvp:FormatText(fmt,keys)
				realm = realm..str
				if j<pcount then realm=realm..', ' end
				
				--healers
				if tContains(specHealers,spec) then
                    hstr = ((hcount==0 and hstr) or hstr..', ')..str
					hcount = hcount+1
                end
			end
			print(color..realm)
		end
		pvp:Print(format("|cffff0000HEALERS|r (%d)%s - ",hcount,color)..hstr)	
		pvp:Print(count..((count~=1 and " players ") or "player ").."detected.")      
    end  

--------------------------------------------------------------------------------------------------
    local function SpyPrintGlobal()
    --[[ 
		broadcast spy information to chat channels
		this and SpyPrintLocal have a lot of overlap, should probably clean that up
	--]]
	
        local roster = GetOpponentRoster()
        local sorted = Sort(roster)
		local COLORS = COLORS
		local count = 0
		local hstr = ""
		local hcount = 0
		local healersonly = pvp.settings.spy.healersonly
		
		local fmt = pvp.settings.spy.globaltext
		
		for i,players in ipairs(sorted) do
			local pcount = #(players)
			count = count + pcount
			local realm = roster[players[1]].realm.." - "
			for j,player in ipairs(players) do
				local class = roster[player].class
				local spec = roster[player].spec
				local keys = {
					["name"] = player,
					["class"] = class,
					["spec"] = spec,
					["altclass"] = pvp.settings.alt.class[class],
					["altspec"] = pvp.settings.alt.spec[class][spec],
				}
				
				local str = pvp:FormatText(fmt,keys)
				realm = realm..str
				if j<pcount then realm=realm..', ' end
				
				--healers
				if tContains(specHealers,spec) then
                    hstr = ((hcount==0 and hstr) or hstr..', ')..str
					hcount = hcount+1
                end
			end
			if not healersonly then
				--SendChatMessage(realm,"INSTANCE_CHAT")
				pvp:Broadcast(realm)
			end
		end
		--SendChatMessage(format("ENEMY HEALERS (%d) - %s",hcount,hstr), "INSTANCE_CHAT")
		pvp:Broadcast(format("ENEMY HEALERS (%d) - %s",hcount,hstr))
    end
  
--------------------------------------------------------------------------------------------------
	function pvp:GetPlayerSpec(name)
	--[[
		returns the spec of the named player
		used for flag carriers
	--]]
		local roster = roster
		if roster[name] then --check if player already exists in roster
			return roster[name].spec
		else
			roster = GetOpponentRoster()
			if roster[name] then
				return roster[name].spec
			else --player still can't be found
				test:Log(name.." was not found on opponent roster.")
				return "?"
			end
		end	    
	end

--------------------------------------------------------------------------------------------------
	function pvp:RequestBattlefieldScoreData()
		RequestBattlefieldScoreData()
		last = time()
	end
 
--------------------------------------------------------------------------------------------------
    function pvp:Spy(button)
	--[[
		spy on opposing team
	--]]
        if pvp.mode == "all" then
            pvp:Print("You are not in a battleground.")
            return
        end
		
		local func = (button=="RightButton" and SpyPrintGlobal) or SpyPrintLocal		
		local t = time()
		
		if not last or t >= last+5 then       
			pvp:Print("Fetching fresh battleground data.")
			pvp:RegisterEvent("UPDATE_BATTLEFIELD_SCORE", 
				function()					
					func()
					pvp:UnregisterEvent("UPDATE_BATTLEFIELD_SCORE")
				end
			)
			pvp:RequestBattlefieldScoreData()
		else
			func()
		end			
    end
	
end --eof 